import axios from "axios";
import router from "../router";
import store from "../store/store";
// import Qs from "qs";
import {
  message as Message
} from './resetMessage.js';


// 创建axios 实例
axios.defaults.headers.post["Content-Type"] = "application/json";
// axios.defaults.paramsSerializer = function(params) {
//   // 格式化数据
//   return Qs.stringify(params, { arrayFormat: "repeat" });
// };
store.state.token = sessionStorage.getItem('token');
const service = axios.create({
  baseURL: process.env.VUE_APP_SSO, // api的base_url
  timeout: 15000, // 请求超时时间
});
// request 拦截器
service.interceptors.request.use(
  (config) => {
    // 这里可以自定义一些config 配置
    // console.log(store.getters.token);
    const tokenStr =JSON.parse(window.localStorage.getItem('XIE_XIN'))
    if(tokenStr){
      config.headers.Authorization = 'Bearer ' + tokenStr.access_token
    }else {
      config.headers.Authorization ='Basic cGFyazpwYXJr'
    }
    config.headers.tenantId ='1'
    config.headers.appId ='2'
    return config;
  },
  (error) => {
    // 这里处理一些请求出错的情况
    console.log(error);
    Promise.reject(error);
  }
);
// response 拦截器
service.interceptors.response.use(
  (response) => {
    // 记录token
    // const _auth = response.headers.authorization || "";
    // store.commit("SET_TOKEN", _auth);
    // 这里处理一些response 正常放回时的逻辑
    // var res=response.data
    // if (res.code == 1) {
    //   Message({
    //     showClose: true,
    //     message: res.msg,
    //     type: "error",
    //   });
    //   return Promise.reject(res);
    // } else {
    //   return res;
    // }
    const { code } = response.data
    if(code!==0){
      return Promise.reject(response);
    }
    return response
  },
  (error) => {
    if (error.response) {
      switch (error.response.status) {
        case 401: {
          Message({
            showClose: true,
            message: "登录超时，请重新登录",
            type: "error",
          });
          // store.commit('breadListStateRemoveAll')
          window.localStorage.removeItem('XIE_XIN')
          store.state.token=''
          router.push({
            path: "/login",
          });
          break;
        }
        case 403: {
          Message({
            showClose: true,
            message: "禁止访问",
            type: "error",
          });
          break;
        }
        default: {
          _runError(error);
        }
      }
    } else {
      if (error.code === "ECONNABORTED") {
        Message({
          showClose: true,
          message: "请求超时！",
          type: "warning",
        });
      } else {
        _runError(error);
      }
    }
    return Promise.reject(error);
  }
);

// 添加统一异常处理方法
let _runError = function(error, form) {
  // 直接显示错误信息
  let result = false;
  const _data = error.response.data;
  const _validates = _data.invalidMessages;
  if (!form || !_validates) {
    Message({
      message: _data.errorMessage,
      type: "error",
      duration: 3000,
    });
    return result;
  }
  const fields = form.fields;
  if (fields) {
    let field = null;
    for (let i = 0, count = fields.length; i < count; i++) {
      field = fields[i];
      if (_validates[field.prop]) {
        field.validateState = "error";
        const msg = _validates[field.prop];
        // if (vm) {
        //   msg = vm.$t(_validates[field.prop]) || msg
        // }
        field.validateMessage = msg;
        result = true;
      }
    }
  }
  return result;
};

export default service;
